<template>
    <div class="container">
        <Breadcrumb :items="['menu.store', 'menu.store.pickUpPoint']" />
        <a-card :title="$t('menu.store.pickUpPoint')">
            <a-space fill direction="vertical" size="large">
                
                <!-- 搜索表单 -->
                <a-row>
                    <a-col :flex="1">
                        <a-form :model="searchForm">
                            <a-row :gutter="16">
                                <a-col :span="4">
                                    <a-form-item field="name" label="配送点名称" hide-label>
                                        <a-input
                                            v-model="searchForm.name"
                                            placeholder="请输入配送点名称"
                                            allow-clear
                                        />
                                    </a-form-item>
                                </a-col>
                                <a-col :span="4">
                                    <a-form-item field="city_id" label="城市" hide-label>
                                        <a-select
                                            v-model="searchForm.city_id"
                                            placeholder="请选择城市"
                                            allow-clear
                                            @change="onCityChange"
                                        >
                                            <a-option
                                                v-for="city in cityList"
                                                :key="city.id"
                                                :value="city.id"
                                            >
                                                {{ city.name }}
                                            </a-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="4">
                                    <a-form-item field="status" label="状态" hide-label>
                                        <a-select
                                            v-model="searchForm.status"
                                            placeholder="请选择状态"
                                            allow-clear
                                        >
                                            <a-option :value="1">启用</a-option>
                                            <a-option :value="0">禁用</a-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-space>
                                        <a-button type="primary" @click="search">
                                            <template #icon>
                                                <icon-search />
                                            </template>
                                            搜索
                                        </a-button>
                                        <a-button @click="reset">
                                            <template #icon>
                                                <icon-refresh />
                                            </template>
                                            重置
                                        </a-button>
                                    </a-space>
                                </a-col>
                            </a-row>
                        </a-form>
                    </a-col>
                </a-row>

                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-space fill>
                            <a-button type="primary" @click="openModal()" shape="round">
                                <template #icon><icon-plus /></template>
                                添加配送点
                            </a-button>
                        </a-space>
                    </a-col>
                    <a-col :flex="1">
                        <a-space align="end" style="justify-content: flex-end;" fill>
                            <a-button shape="circle" @click="resetSearch">
                                <template #icon><icon-refresh /></template>
                            </a-button>
                        </a-space>
                    </a-col>
                </a-row>

                <a-table :data="renderData" :loading="loading" :bordered="{ cell: true }" :pagination="pagination"
                    @page-change="onPageChange" @page-size-change="onPageSizeChange">
                    <template #columns>
                        <a-table-column title="ID" data-index="id" :width="80" />
                        <a-table-column title="配送点名称" data-index="name" :width="150" />
                        <a-table-column title="省份" data-index="province" :width="100" />
                        <a-table-column title="城市" data-index="city" :width="100" />
                        <a-table-column title="区域" data-index="area" :width="100" />
                        <a-table-column title="详细地址" data-index="address" :width="200" />
                        <a-table-column title="联系电话" data-index="phone" :width="120" />
                        <a-table-column title="状态" data-index="status_text" :width="80">
                            <template #cell="{ record }">
                                <a-tag :color="record.status ? 'green' : 'red'">
                                    {{ record.status_text }}
                                </a-tag>
                            </template>
                        </a-table-column>
                        <a-table-column title="创建时间" data-index="created_at" :width="180" />
                        <a-table-column title="操作" :width="150" fixed="right">
                            <template #cell="{ record }">
                                <a-space>
                                    <a-link type="text" size="small" @click="openModal(record)">
                                        编辑
                                    </a-link>
                                    <a-link 
                                        type="text" 
                                        size="small" 
                                        :color="record.status ? 'red' : 'green'"
                                        @click="toggleStatus(record)"
                                    >
                                        {{ record.status ? '禁用' : '启用' }}
                                    </a-link>
                                    <a-popconfirm
                                        content="确定要删除这个配送点吗？"
                                        @ok="deleteRecord(record)"
                                    >
                                        <a-link type="text" size="small" status="danger">
                                            
                                            删除
                                        </a-link>
                                    </a-popconfirm>
                                </a-space>
                            </template>
                        </a-table-column>
                    </template>
                </a-table>
            </a-space>
        </a-card>

        <!-- 添加/编辑弹窗 -->
        <a-modal
            v-model:visible="modalVisible"
            :title="formData.id ? '编辑配送点' : '添加配送点'"
            @ok="submitForm"
            @cancel="closeModal"
            :confirm-loading="submitLoading"
            width="600px"
        >
            <a-form :model="formData" ref="formRef" :rules="formRules" layout="vertical">
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item field="name" label="配送点名称" required>
                            <a-input v-model="formData.name" placeholder="请输入配送点名称" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item field="phone" label="联系电话" required>
                            <a-input v-model="formData.phone" placeholder="请输入联系电话" />
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="16">
                    <a-col :span="8">
                        <a-form-item field="province" label="省份" required>
                            <a-input v-model="formData.province" placeholder="请输入省份" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item field="city" label="城市" required>
                            <a-input v-model="formData.city" placeholder="请输入城市" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item field="area" label="区域">
                            <a-input v-model="formData.area" placeholder="请输入区域" />
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item field="city_id" label="城市ID" required>
                            <a-select
                                v-model="formData.city_id"
                                placeholder="请选择城市"
                                allow-search
                            >
                                <a-option
                                    v-for="city in cityList"
                                    :key="city.id"
                                    :value="city.id"
                                >
                                    {{ city.name }}
                                </a-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item field="status" label="状态">
                            <a-select v-model="formData.status" placeholder="请选择状态">
                                <a-option :value="1">启用</a-option>
                                <a-option :value="0">禁用</a-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-form-item field="address" label="详细地址" required>
                    <a-textarea v-model="formData.address" placeholder="请输入详细地址" :rows="3" />
                </a-form-item>
                <a-form-item field="gps" label="GPS坐标">
                    <a-input v-model="formData.gps" placeholder="请输入GPS坐标，如：116.397128,39.916527" />
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { Message } from '@arco-design/web-vue';
import { 
    queryPickUpPointList, 
    createPickUpPoint, 
    updatePickUpPoint, 
    delPickUpPoint, 
    updatePickUpPointStatus,
    type PickUpPointRecord,
    type PickUpPointModel,
    type PickUpPointParams
} from '@/api/pickUpPoint';
import { queryCityList, type CityRecord } from '@/api/city';

// 响应式数据
const loading = ref(false);
const modalVisible = ref(false);
const submitLoading = ref(false);
const cityList = ref<CityRecord[]>([]);
const renderData = ref<PickUpPointRecord[]>([]);
const total = ref(0);

// 搜索表单
const searchForm = reactive<PickUpPointParams>({
    current: 1,
    pageSize: 10,
    name: '',
    city_id: undefined,
    status: undefined
});

// 表单数据
const formData = reactive<PickUpPointModel>({
    name: '',
    province: '',
    city: '',
    area: '',
    address: '',
    gps: '',
    phone: '',
    city_id: '',
    status: 1
});

// 表单验证规则
const formRules = {
    name: [{ required: true, message: '请输入配送点名称' }],
    province: [{ required: true, message: '请输入省份' }],
    city: [{ required: true, message: '请输入城市' }],
    address: [{ required: true, message: '请输入详细地址' }],
    phone: [{ required: true, message: '请输入联系电话' }],
    city_id: [{ required: true, message: '请选择城市' }]
};

// 分页配置
const pagination = computed(() => ({
    total: total.value,
    current: searchForm.current,
    pageSize: searchForm.pageSize,
    showTotal: true,
    showJumper: true,
    showPageSize: true
}));

// 表单引用
const formRef = ref();



// 获取城市列表
const fetchCityList = async () => {
    try {
        const response = await queryCityList({ page: 1, pageSize: 1000 });
        if (response.code === 20000) {
            cityList.value = response.data.list;
        }
    } catch (error) {
        console.error('获取城市列表失败:', error);
    }
};

// 获取数据
const fetchData = async () => {
    loading.value = true;
    try {
        const response = await queryPickUpPointList(searchForm);
        
        if (response.code === 20000) {
            renderData.value = response.data.list;
            total.value = response.data.total;
        } else {
            Message.error(response.msg || '获取数据失败');
        }
    } catch (error) {
        console.error('获取数据失败:', error);
        Message.error('获取数据失败');
    } finally {
        loading.value = false;
    }
};

// 搜索
const search = () => {
    searchForm.current = 1;
    fetchData();
};

// 重置搜索
const reset = () => {
    searchForm.name = '';
    searchForm.city_id = undefined;
    searchForm.status = undefined;
    search();
};

// 重置搜索并刷新
const resetSearch = () => {
    reset();
};

// 城市选择变化
const onCityChange = () => {
    // 可以在这里添加城市选择后的逻辑
};

// 分页变化
const onPageChange = (current: number) => {
    searchForm.current = current;
    fetchData();
};

const onPageSizeChange = (pageSize: number) => {
    searchForm.pageSize = pageSize;
    searchForm.current = 1;
    fetchData();
};

// 打开弹窗
const openModal = (record?: PickUpPointRecord) => {
    if (record) {
        // 编辑模式
        Object.assign(formData, record);
    } else {
        // 添加模式
        Object.assign(formData, {
            id: undefined,
            name: '',
            province: '',
            city: '',
            area: '',
            address: '',
            gps: '',
            phone: '',
            city_id: 0,
            status: 1
        });
    }
    modalVisible.value = true;
};

// 关闭弹窗
const closeModal = () => {
    modalVisible.value = false;
    formRef.value?.resetFields();
};

// 提交表单
const submitForm = async () => {
    try {
        await formRef.value?.validate();
        submitLoading.value = true;
        
        let response;
        if (formData.id) {
            // 更新
            response = await updatePickUpPoint(formData);
        } else {
            // 创建
            response = await createPickUpPoint(formData);
        }
        
        if (response.code === 20000) {
            Message.success(response.msg || '操作成功');
            closeModal();
            fetchData();
        } else {
            Message.error(response.msg || '操作失败');
        }
    } catch (error) {
        console.error('提交失败:', error);
        Message.error('提交失败');
    } finally {
        submitLoading.value = false;
    }
};

// 切换状态
const toggleStatus = async (record: PickUpPointRecord) => {
    try {
        const newStatus = record.status ? 0 : 1;
        const response = await updatePickUpPointStatus({
            id: record.id,
            status: newStatus
        });
        
        if (response.code === 20000) {
            Message.success(response.msg || '状态更新成功');
            fetchData();
        } else {
            Message.error(response.msg || '状态更新失败');
        }
    } catch (error) {
        console.error('状态更新失败:', error);
        Message.error('状态更新失败');
    }
};

// 删除记录
const deleteRecord = async (record: PickUpPointRecord) => {
    try {
        const response = await delPickUpPoint(record.id);
        if (response.code === 20000) {
            Message.success(response.msg || '删除成功');
            fetchData();
        } else {
            Message.error(response.msg || '删除失败');
        }
    } catch (error) {
        console.error('删除失败:', error);
        Message.error('删除失败');
    }
};

// 初始化
onMounted(() => {
    fetchData();
    fetchCityList();
});
</script>

<style scoped>
.container {
    padding: 20px;
}
</style>
